package wang.lx.mybatis.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.log4j.Log4j2;
import wang.lx.mybatis.common.ResponseMessage;
import wang.lx.mybatis.entity.SysUser;
import wang.lx.mybatis.service.SysUserService;

/**
 * @Description: 用户登录
 * @Author: 王的世界
 * @Date: 2025/07/06 20:50:26
*/
@Log4j2
@RestController
@RequestMapping("/login")
public class LoginController {

    private final SysUserService sysUserService;

    LoginController(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }
    
    /**
     * @Description: 登录
     * @Author: 王的世界
     * @Date: 2025/07/07
     * @param account 账号
     * @param password 密码
     * @return
     */
    @PostMapping(value="/")
    public ResponseMessage<Object> login(String account,String password) {
        AuthenticationToken token = new UsernamePasswordToken(account,password);
        Subject subject = SecurityUtils.getSubject();
        String jwttoken = null;
        try
        {
            subject.login(token);
            // 登录成功后，获取登录用户
            SysUser user = (SysUser)subject.getPrincipal();
            jwttoken = this.sysUserService.genUserToken(user);
        }
        catch(AccountException userPwdExcetion)
        {
            return ResponseMessage.error(null,"用户名或密码错误");
        }
        catch(Exception e)
        {
            log.error("登录异常",e);
            return ResponseMessage.error(null,"登录失败");
        }
        return ResponseMessage.success(jwttoken);
    }

    /**
     * 退出登录
     * @return
     */
    public ResponseMessage<Object> logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResponseMessage.success(null);
    }
}
